package com.example.sunmiv1.utils.zxing.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.sunmiv1.R;
import com.example.sunmiv1.activity.NewInventoryActivity;
import com.example.sunmiv1.adapter.ScanGoodAdapter;
import com.example.sunmiv1.entity.AllocationGoodsInfo;
import com.example.sunmiv1.entity.DepositGoodsInfo;
import com.example.sunmiv1.entity.GoodsStoreRetreatInfo;
import com.example.sunmiv1.entity.LossGoodsInfo;
import com.example.sunmiv1.entity.ReportLossGoodBean;
import com.example.sunmiv1.entity.ScanGoodInfo;
import com.example.sunmiv1.utils.LogUtil;
import com.example.sunmiv1.utils.Tools;
import com.example.sunmiv1.utils.net.ACache;
import com.example.sunmiv1.utils.net.Common;
import com.example.sunmiv1.utils.net.GsonUtils;
import com.example.sunmiv1.utils.net.HttpUtils;
import com.example.sunmiv1.utils.net.TextCallBack;
import com.example.sunmiv1.utils.zxing.Constant;
import com.example.sunmiv1.utils.zxing.ScanGoodCallback;
import com.example.sunmiv1.utils.zxing.camera.CameraManager;
import com.example.sunmiv1.utils.zxing.decoding.CaptureActivityHandler;
import com.example.sunmiv1.utils.zxing.decoding.DecodeHandler;
import com.example.sunmiv1.utils.zxing.decoding.InactivityTimer;
import com.example.sunmiv1.utils.zxing.decoding.RGBLuminanceSource;
import com.example.sunmiv1.utils.zxing.view.ViewfinderView;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.ChecksumException;
import com.google.zxing.DecodeHintType;
import com.google.zxing.FormatException;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.QRCodeReader;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.Vector;

import butterknife.BindView;
import butterknife.ButterKnife;


/**
 * Initial the camera
 *
 * @author Ryan.Tang
 */
public class ScanGoodActivity<T> extends AppCompatActivity implements Callback {

    private static final int REQUEST_CODE_SCAN_GALLERY = 100;
    private static final String TAG = "TAG";
    @BindView(R.id.title_back)
    ImageView titleBack;
    @BindView(R.id.title_title)
    TextView titleTitle;
    @BindView(R.id.scanner_view)
    SurfaceView scannerView;
    @BindView(R.id.viewfinder_content)
    ViewfinderView viewfinderContent;
    @BindView(R.id.scanGood_listView)
    ListView scanGoodListView;
    @BindView(R.id.scanGood_confirm)
    TextView scanGoodConfirm;

    private CaptureActivityHandler handler;
    private boolean hasSurface;
    private Vector<BarcodeFormat> decodeFormats;
    private String characterSet;
    private InactivityTimer inactivityTimer;
    private boolean vibrate;
    private Bitmap scanBitmap;
    /**
     * Called when the activity is first created.
     */


    private ACache aCache;
    private int scannerType = 0;//報損/盤點/採購/採購退貨/出庫    1/2/3/4/5


    private List<LossGoodsInfo.DataBean> choiceList;//報損集合

    private List<ReportLossGoodBean.DataBean.ListBean> reportLossList;//盤點集合

    private List<DepositGoodsInfo.DataBean.ListBean> depositGoodsList;//採購集合

    private List<GoodsStoreRetreatInfo.DataBean> retreatGoodsList;//採購退貨集合

    private List<AllocationGoodsInfo.DataBean> allocationGoodsList;//出庫單集合

    private ScanGoodAdapter scanGoodAdapter;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_scan_good);
        ButterKnife.bind(this);
        aCache = ACache.get(this);
        scannerType = getIntent().getIntExtra("scannerType", 0);
        switch (scannerType) {
            case 1:
                choiceList = (List<LossGoodsInfo.DataBean>) getIntent().getSerializableExtra("list");
                setScanGoodAdapter((List<T>) choiceList);
                break;
            case 2:
                order_id = aCache.getAsString("order_id");
                reportLossList = (List<ReportLossGoodBean.DataBean.ListBean>) getIntent().getSerializableExtra("list");
                setScanGoodAdapter((List<T>) reportLossList);
                break;
            case 3:
                depositGoodsList = (List<DepositGoodsInfo.DataBean.ListBean>) getIntent().getSerializableExtra("list");
                setScanGoodAdapter((List<T>) depositGoodsList);
                break;
            case 4:
                retreatGoodsList = (List<GoodsStoreRetreatInfo.DataBean>) getIntent().getSerializableExtra("list");
                setScanGoodAdapter((List<T>) retreatGoodsList);
                break;
            case 5:
                allocationGoodsList = (List<AllocationGoodsInfo.DataBean>) getIntent().getSerializableExtra("list");
                setScanGoodAdapter((List<T>) allocationGoodsList);
                break;
            default:
                break;
        }
        //ViewUtil.addTopView(getApplicationContext(), this, R.string.scan_card);
        CameraManager.init(getApplication());
        getSupportActionBar().hide();
        titleBack = findViewById(R.id.title_back);
        titleBack.setVisibility(View.VISIBLE);
        titleBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                backAndFinish();
            }
        });
        titleTitle = findViewById(R.id.title_title);
        titleTitle.setText("二維碼");
//		cancelScanButton = (Button) this.findViewById(R.id.btn_cancel_scan);
        hasSurface = false;
        inactivityTimer = new InactivityTimer(this);


        if (scannerType != 0) {
            if (searchTimer == null) {
                Log.e(TAG, "onSuccess: 8251");
                searchTimer = new Timer();
            }
            searchTask = new SearchTimerTask();
            searchTimer.schedule(searchTask, 0, 3000);
        }

        scanGoodConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                backAndFinish();
            }
        });

        //添加toolbar
//        addToolbar();
    }

    private void backAndFinish() {
        if (searchTimer != null && searchTask != null) {
            Log.e(TAG, "onSuccess: 8245");
            searchTimer.cancel();
            searchTimer.purge();
            searchTimer = null;
            searchTask.cancel();
        }
        Intent resultIntent = new Intent();
        Bundle bundle = new Bundle();
        switch (scannerType) {
            case 1:
                bundle.putSerializable("list", (Serializable) choiceList);
                break;
            case 2:
                bundle.putSerializable("list", (Serializable) reportLossList);
                break;
            case 3:
                bundle.putSerializable("list", (Serializable) depositGoodsList);
                break;
            case 4:
                bundle.putSerializable("list", (Serializable) retreatGoodsList);
                break;
            case 5:
                bundle.putSerializable("list", (Serializable) allocationGoodsList);
                break;
            default:
                break;
        }
        resultIntent.putExtras(bundle);
        setResult(RESULT_OK, resultIntent);
        finish();
    }


    private void setScanGoodAdapter(List<T> list) {
        scanGoodAdapter = new ScanGoodAdapter(getSupportFragmentManager(), list, scannerType);
        scanGoodListView.setAdapter(scanGoodAdapter);
    }


    @Override
    protected void onResume() {
        super.onResume();
        SurfaceHolder surfaceHolder = scannerView.getHolder();
        if (hasSurface) {
            initCamera(surfaceHolder);
        } else {
            surfaceHolder.addCallback(this);
            surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        }
        decodeFormats = null;
        characterSet = null;

        vibrate = true;
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (handler != null) {
            handler.quitSynchronously();
            handler = null;
        }
        CameraManager.get().closeDriver();
    }

    @Override
    protected void onDestroy() {
        inactivityTimer.shutdown();
        super.onDestroy();
    }

    private Timer searchTimer;
    private SearchTimerTask searchTask;
    private int time = 0;

    private String order_id = "";

    private class SearchTimerTask extends TimerTask {
        @Override
        public void run() {
            time += 3;
            if (scannerType == 2) {
                if (time > 60 && time % 21 == 0) {
                    if (reportLossList.size() > 0) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                submitInventory();
                            }
                        });
                    }
                }
            }
            try {
                handler.restartPreviewAndDecode(); // 實現多次掃描
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 報損掃描商品
     */
    private void lossScanCodeGoods(String info) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("search_info", info);
            jsonObject = Tools.createParameterCode(jsonObject);
            HttpUtils.post(this, Common.LOSS_SCAN_CODE_GOODS, jsonObject, new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
                    try {
                        JSONObject json = new JSONObject(text);
                        Toast.makeText(ScanGoodActivity.this, json.getString("message"), Toast.LENGTH_SHORT).show();
                        if (json.getInt("status") == 1) {
                            ScanGoodInfo scanGoodInfo = GsonUtils.JsonToBean(text, ScanGoodInfo.class);
                            scanGoodInfo.getData().setLoss_num(1);
                            boolean flag = false;
                            for (int i = 0; i < choiceList.size(); i++) {
                                if (choiceList.get(i).getId().equals(scanGoodInfo.getData().getId())) {
                                    flag = true;
                                    choiceList.get(i).setLoss_num((Double.parseDouble(choiceList.get(i).getLoss_num()) + 1) + "");
                                }
                            }
                            if (!flag) {
                                choiceList.add(new LossGoodsInfo.DataBean(scanGoodInfo.getData()));
                            }
                            setScanGoodAdapter((List<T>) choiceList);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }

                @Override
                protected void onFailure(ResponseException e) {

                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 盤點掃描商品
     */
    private void reportScanCodeGoods(String info) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("search_info", info);
            jsonObject = Tools.createParameterCode(jsonObject);
            HttpUtils.post(this, Common.INVENTORY_SCAN_CODE_GOODS, jsonObject, new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
                    try {
                        JSONObject json = new JSONObject(text);
                        Toast.makeText(ScanGoodActivity.this, json.getString("message"), Toast.LENGTH_SHORT).show();
                        if (json.getInt("status") == 1) {
                            ScanGoodInfo scanGoodInfo = GsonUtils.JsonToBean(text, ScanGoodInfo.class);
                            scanGoodInfo.getData().setInventory_num(1);
                            boolean flag = false;
                            for (int i = 0; i < reportLossList.size(); i++) {
                                if (reportLossList.get(i).getId().equals(scanGoodInfo.getData().getId())) {
                                    flag = true;
                                    if (!"1".equals(reportLossList.get(i).getSerial_number_state())) {
                                        reportLossList.get(i).setInventory_num((Double.parseDouble(reportLossList.get(i).getInventory_num()) + 1) + "");
                                    }
                                }
                            }
                            if (!flag) {
                                ReportLossGoodBean.DataBean.ListBean bean = new ReportLossGoodBean.DataBean.ListBean(scanGoodInfo.getData());
                                bean.setInventory_num("0");
                                reportLossList.add(bean);
                            }
                            setScanGoodAdapter((List<T>) reportLossList);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }

                @Override
                protected void onFailure(ResponseException e) {

                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    /**
     * 採購掃描商品
     */
    private void purScanGood(String info) {
        JSONObject jsonObject = new JSONObject();
        try {
            String url = "";
            if ("1".equals(aCache.getAsString("userType"))) {
                url = Common.MER_PUR_SCAN_CODE_GOODS;
            } else {
                url = Common.STORE_PUR_SCAN_CODE_GOODS;
            }
            jsonObject.put("search_info", info);
            jsonObject = Tools.createParameterCode(jsonObject);
            HttpUtils.post(this, url, jsonObject, new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
                    try {
                        JSONObject json = new JSONObject(text);
                        Toast.makeText(ScanGoodActivity.this, json.getString("message"), Toast.LENGTH_SHORT).show();
                        if (json.getInt("status") == 1) {
                            ScanGoodInfo scanGoodInfo = GsonUtils.JsonToBean(text, ScanGoodInfo.class);
                            scanGoodInfo.getData().setPurchase_num(1);
                            boolean flag = false;
                            for (int i = 0; i < depositGoodsList.size(); i++) {
                                if (depositGoodsList.get(i).getId().equals(scanGoodInfo.getData().getId())) {
                                    flag = true;
                                    depositGoodsList.get(i).setPurchase_num((Double.parseDouble(depositGoodsList.get(i).getPurchase_num()) + 1) + "");
                                }
                            }
                            if (!flag) {
                                depositGoodsList.add(new DepositGoodsInfo.DataBean.ListBean(scanGoodInfo.getData()));
                            }
                            setScanGoodAdapter((List<T>) depositGoodsList);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }

                @Override
                protected void onFailure(ResponseException e) {

                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    /**
     * 採購退貨掃描商品
     */
    private void retreatScanGood(String info) {
        JSONObject jsonObject = new JSONObject();
        try {
            String url = "";
            if ("1".equals(aCache.getAsString("userType"))) {
                url = Common.MER_RETREAT_SCAN_CODE_GOODS;
            } else {
                url = Common.STORE_RETREAT_SCAN_CODE_GOODS;
            }
            jsonObject.put("supplier_id", aCache.getAsString("supplier_id"));
            jsonObject.put("warehouse_id", aCache.getAsString("warehouse_id"));
            jsonObject.put("search_info", info);
            jsonObject = Tools.createParameterCode(jsonObject);
            HttpUtils.post(this, url, jsonObject, new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
                    try {
                        JSONObject json = new JSONObject(text);
                        Toast.makeText(ScanGoodActivity.this, json.getString("message"), Toast.LENGTH_SHORT).show();
                        if (json.getInt("status") == 1) {
                            ScanGoodInfo scanGoodInfo = GsonUtils.JsonToBean(text, ScanGoodInfo.class);
                            scanGoodInfo.getData().setRetreat_num_act(1);
                            boolean flag = false;
                            for (int i = 0; i < retreatGoodsList.size(); i++) {
                                if (retreatGoodsList.get(i).getId().equals(scanGoodInfo.getData().getId())) {
                                    flag = true;
                                    retreatGoodsList.get(i).setRetreat_num_act(retreatGoodsList.get(i).getRetreat_num_act() + 1);
                                }
                            }
                            if (!flag) {
                                retreatGoodsList.add(new GoodsStoreRetreatInfo.DataBean(scanGoodInfo.getData()));
                            }
                            setScanGoodAdapter((List<T>) retreatGoodsList);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }

                @Override
                protected void onFailure(ResponseException e) {

                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 出庫掃描商品
     */
    private void allocationScanGood(String info) {
        JSONObject jsonObject = new JSONObject();
        try {
            String url = "";
            if ("1".equals(aCache.getAsString("userType"))) {
                url = Common.Allocate_SCAN_CODE_GOODS;
            } else {
                url = Common.S_STOCK_SCAN_CODE_GOODS_V1;
                jsonObject.put("type", aCache.getAsString("addAllocationType"));
            }
            jsonObject.put("search_info", info);
            jsonObject = Tools.createParameterCode(jsonObject);
            HttpUtils.post(this, url, jsonObject, new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
                    try {
                        JSONObject json = new JSONObject(text);
                        Toast.makeText(ScanGoodActivity.this, json.getString("message"), Toast.LENGTH_SHORT).show();
                        if (json.getInt("status") == 1) {
                            ScanGoodInfo scanGoodInfo = GsonUtils.JsonToBean(text, ScanGoodInfo.class);
                            scanGoodInfo.getData().setOutput_num(1);
                            boolean flag = false;
                            for (int i = 0; i < allocationGoodsList.size(); i++) {
                                if (allocationGoodsList.get(i).getId().equals(scanGoodInfo.getData().getId())) {
                                    flag = true;
                                    allocationGoodsList.get(i).setOutput_num((Double.parseDouble(allocationGoodsList.get(i).getOutput_num()) + 1) + "");
                                }
                            }
                            if (!flag) {
                                allocationGoodsList.add(new AllocationGoodsInfo.DataBean(scanGoodInfo.getData()));
                            }
                            setScanGoodAdapter((List<T>) allocationGoodsList);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }

                @Override
                protected void onFailure(ResponseException e) {

                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 提交盤點
     */
    private void submitInventory() {
        JSONObject jsonObject = new JSONObject();
        JSONArray jsonArray = new JSONArray();
        try {
            jsonObject.put("user_type", aCache.getAsString("userType"));
            for (int i = 0; i < reportLossList.size(); i++) {
                JSONObject json = new JSONObject();
                json.put("id", reportLossList.get(i).getId());
                json.put("warehouse_id", reportLossList.get(i).getWarehouse_id());
                json.put("goods_id", reportLossList.get(i).getGoods_id());
                json.put("goods_name", reportLossList.get(i).getGoods_name());
                json.put("goods_number", reportLossList.get(i).getGoods_number());
                json.put("goods_code", reportLossList.get(i).getGoods_code());
                json.put("attribute_state", reportLossList.get(i).getAttribute_state());
                json.put("sku_id", reportLossList.get(i).getSku_id());
                json.put("sku_code", reportLossList.get(i).getSku_code());
                json.put("sku_name", reportLossList.get(i).getSku_name());
                json.put("sku_num", reportLossList.get(i).getSku_num());
                json.put("sku_goods_number", reportLossList.get(i).getSku_goods_number());
                json.put("goods_num", reportLossList.get(i).getGoods_num());
                json.put("more_num", reportLossList.get(i).getMore_num());
                json.put("less_num", reportLossList.get(i).getLess_num());
                json.put("inventory_num", reportLossList.get(i).getInventory_num());
                json.put("cost_price", reportLossList.get(i).getCost_price());
                json.put("purchase_order_id", reportLossList.get(i).getPurchase_order_id());
                json.put("company", reportLossList.get(i).getCompany());
                json.put("inventory_goods_id", reportLossList.get(i).getInventory_goods_id());
                LogUtil.e("");
                jsonArray.put(json);
            }
            jsonObject.put("goodsList", jsonArray);
            jsonObject.put("submit_type", 3);//1盤點 2保存草稿箱 3實時盤點 按鈕類型
            jsonObject.put("order_id", order_id);//通過繼續盤點按鈕點擊去的頁面提交必須傳盤點訂單id
            jsonObject = Tools.createParameterCode(jsonObject);
            HttpUtils.post(this, Common.SUBMIT_INVENTORY, jsonObject, new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
                    try {
                        JSONObject json = new JSONObject(text);
                        if (json.getInt("status") == 1) {
                            order_id = json.getJSONObject("data").getString("order_id");
                            aCache.put("order_id", order_id);
                            order_id = json.getJSONObject("data").getString("order_id");
                            JSONArray arr = json.getJSONObject("data").getJSONArray("record_id_arr");
                            for (int i = 0; i < reportLossList.size(); i++) {
                                for (int s = 0; s < arr.length(); s++) {
                                    JSONObject d = arr.getJSONObject(s);
                                    if ("2".equals(d.getString("attribute_state"))) {
                                        if (reportLossList.get(i).getGoods_id().equals(d.getString("goods_id")) &&
                                                reportLossList.get(i).getSku_id().equals(d.getString("sku_id"))) {
                                            reportLossList.get(i).setInventory_goods_id(d.getString("inventory_goods_id"));
                                        }
                                    } else {
                                        if (reportLossList.get(i).getGoods_id().equals(d.getString("goods_id"))) {
                                            reportLossList.get(i).setInventory_goods_id(d.getString("inventory_goods_id"));
                                        }
                                    }
                                }
                            }
                        }
//                        Toast.makeText(ScanGoodActivity.this, json.getString("message"), Toast.LENGTH_SHORT).show();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                protected void onFailure(ResponseException e) {

                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    private void initCamera(SurfaceHolder surfaceHolder) {
        try {
            CameraManager.get().openDriver(surfaceHolder);
        } catch (IOException ioe) {
            return;
        } catch (RuntimeException e) {
            return;
        }
        if (handler == null) {
            handler = new CaptureActivityHandler(this, decodeFormats, characterSet, viewfinderContent, new ScanGoodCallback() {
                @Override
                public void success(Result result, Bitmap barcode) {
                    Log.e(TAG, "handleDecode: result==========" + result.getText());
                    inactivityTimer.onActivity();
                    playBeepSoundAndVibrate();
                    String resultString = result.getText();
                    if (TextUtils.isEmpty(resultString)) {
                        Toast.makeText(ScanGoodActivity.this, "Scan failed!", Toast.LENGTH_SHORT).show();
                        ScanGoodActivity.this.finish();
                    } else {
                        if (scannerType != 0) {
                            switch (scannerType) {
                                case 1:
                                    lossScanCodeGoods(resultString);
                                    break;
                                case 2:
                                    reportScanCodeGoods(resultString);
                                    break;
                                case 3:
                                    purScanGood(resultString);
                                    break;
                                case 4:
                                    retreatScanGood(resultString);
                                    break;
                                case 5:
                                    allocationScanGood(resultString);
                                    break;
                                default:
                                    break;
                            }
                        } else {
                            Intent resultIntent = new Intent();
                            Bundle bundle = new Bundle();
                            bundle.putString(Constant.INTENT_EXTRA_KEY_QR_SCAN, resultString);
                            resultIntent.putExtras(bundle);
                            setResult(RESULT_OK, resultIntent);
                            ScanGoodActivity.this.finish();
                        }
                    }
                }
            });
            DecodeHandler.handler = handler;
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width,
                               int height) {

    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        if (!hasSurface) {
            hasSurface = true;
            initCamera(holder);
        }

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        hasSurface = false;

    }

    public Handler getHandler() {
        return handler;
    }

    private static final long VIBRATE_DURATION = 200L;

    private void playBeepSoundAndVibrate() {
        if (vibrate) {
            Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
            vibrator.vibrate(VIBRATE_DURATION);
        }
    }

    /**
     * When the beep has finished playing, rewind to queue up another one.
     */
    private final OnCompletionListener beepListener = mediaPlayer -> mediaPlayer.seekTo(0);

}
